import { FoldingAction, FoldingActionTypes } from '../actions/folding.action';
import { Folding } from '../../models';

export interface FoldingState {
    basemaps: Folding;
    layers: Folding;
    spaticlFiltering: Folding;
    measure: Folding;
    grid: Folding;
    resourceTree: Folding;
    upload: Folding;
}

export const initialFoldingState = {
    basemaps: null,
    layers: null,
    spaticlFiltering: null,
    measure: null,
    grid: null,
    resourceTree: null,
    upload: null
}

function handleState(state: FoldingState, payload: Folding, name: string): FoldingState {
    if(payload.deactiveOther && payload.visible) {
        let foldings: { key: string, data: Folding }[] = Object.keys(state).map((key: string) => {
            let folding: Folding = {...state[key]};
            let data: Folding = folding;
            if(folding) {
                let visible: boolean = folding.visible;
                if(folding.deactiveByOther) {
                    visible = false;
                }
                data = {...data, visible};
            }
            return { key, data };
        });
        let newState = foldings.reduce((state: FoldingState, folding: { key: string, data: Folding }) => {
            return { ...state, [folding.key]: folding.data };
        }, state);
        return { ...newState, [name]: payload };
    } else {
        return { ...state, [name]: payload };
    }
}

export function FoldingReducer(state: FoldingState = initialFoldingState, action: FoldingAction): FoldingState {
    switch(action.type) {
        case FoldingActionTypes.SET_BASEMAPS: {
            return handleState(state, action.payload, 'basemaps');
        }
        case FoldingActionTypes.SET_BASEMAPS_THUMBNAIL: {
            if(state.basemaps) {
                const basemaps: Folding = { ...state.basemaps, imgSrc: action.payload };
                return {
                    ...state,
                    basemaps
                }
            }
            return state;
        }
        case FoldingActionTypes.SET_GRID: {
            return handleState(state, action.payload, 'grid');
        }
        case FoldingActionTypes.SET_LAYERS: {
            return handleState(state, action.payload, 'layers');
        }
        case FoldingActionTypes.SET_MEASURE: {
            return handleState(state, action.payload, 'measure');
        }
        case FoldingActionTypes.SET_RESOURCE_TREE: {
            return handleState(state, action.payload, 'resourceTree');
        }
        case FoldingActionTypes.SET_SPATICL_FILTERING: {
            return handleState(state, action.payload, 'spaticlFiltering');
        }
        case FoldingActionTypes.SET_UPLOAD: {
            return handleState(state, action.payload, 'upload');
        }
        default: {
            return state;
        }
    }
}